<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!--  separator-class="el-icon-arrow-right"：设置面包屑中间的连接图标 -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- el-alert：是注意提示框 -->
      <el-alert
        show-icon
        title="注意:只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
      ></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            :options="cateList"
            :props="cascaderProps"
            @change="handleChange"
            v-model="selectKeys"
            expandTrigger="hover"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            :disabled="isBtnDisabled"
            type="primary"
            size="mini"
            @click="addParams"
            >添加动态参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteValsClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editCateParamsDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.id, scope.row.cat_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            :disabled="isBtnDisabled"
            type="primary"
            size="mini"
            @click="addParams"
            >添加静态属性</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="deleteValsClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editCateParamsDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scope.row.id, scope.row.cat_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="dialogVisible"
      width="30%"
      @close="addParamsClose"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsRules"
        ref="addParamsRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数的对话框 -->
    <el-dialog
      :title="'编辑' + titleText"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editParamsClose"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsRules"
        ref="editParamsRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      //  商品分类列表
      cateList: [],
      //  指定级联选择器的配置属性
      cascaderProps: {
        value: 'id',
        label: 'cat_name',
        children: 'children'
      },
      //  级联选择器双向绑定到的数组
      selectKeys: [],
      //  被激活的页签名称
      activeName: 'many',
      //  静态only的数组
      onlyList: [],
      //  动态many的数组
      manyList: [],
      //  显示添加参数对话框
      dialogVisible: false,
      //    添加参数的验证规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', tigger: 'blur' }
        ]
      },
      //  添加参数的数据对象
      addParamsForm: {
        attr_name: '',
        attr_sel: ''
      },
      //  显示隐藏编辑参数的对话框
      editDialogVisible: false,
      //  编辑参数的表单数据
      editParamsForm: {
        attr_name: ''
      },
      //  编辑修改参数的表单验证
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', tigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },

    //  级联选择器选中项发生变化，会触发这个函数
    async handleChange () {
      this.getParamsCate()
    },

    //  获取参数列表
    async getParamsCate () {
      const id = this.selectKeys[this.selectKeys.length - 1]
      const { data: res } = await this.$http.get(
        `categories/${id}/attributes`,
        { params: { attr_sel: this.activeName } }
      )
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        //  每一行的文本值
        item.inputValue = ''
        //  控制每一行的文本框显示
        item.inputVisible = false
      })
      if (this.activeName === 'many') {
        this.manyList = res.data
      } else if (this.activeName === 'only') {
        this.onlyList = res.data
      }
    },

    //  激活tab页的点击事件
    handleTabClick () {
      this.handleChange()
    },

    //  添加参数
    addParams () {
      this.dialogVisible = true
    },

    //  关闭添加参数对话框
    addParamsClose () {
      this.$refs.addParamsRef.resetFields()
    },

    //  添加分类参数
    addCateParams () {
      this.$refs.addParamsRef.validate(async (valid) => {
        if (!valid) return
        this.addParamsForm.attr_sel = this.activeName
        const id = this.selectKeys[this.selectKeys.length - 1]
        const { data: res } = await this.$http.post(
          `categories/${id}/attributes`,
          this.addParamsForm
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('添加新的参数成功')
        this.dialogVisible = false
        this.getParamsCate()
      })
    },

    //  显示编辑参数的对话框
    async editCateParamsDialog (params) {
      const id = params.id
      const catid = params.cat_id
      const attrsel = this.activeName
      const { data: res } = await this.$http.get(
        `categories/${catid}/attributes/${id}`,
        { params: { attr_sel: attrsel } }
      )
      this.editParamsForm = res.data
      this.editDialogVisible = true
    },

    //  关闭编辑参数的对话框
    editParamsClose () {
      this.$refs.editParamsRef.resetFields()
    },

    //  编辑参数的事件
    async editCateParams () {
      this.$refs.editParamsRef.validate(async (vilade) => {
        if (!vilade) return
        const { data: res } = await this.$http.put(
          `categories/${this.editParamsForm.cat_id}/attributes/${this.editParamsForm.id}`,
          this.editParamsForm
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('修改参数名称成功')
        this.getParamsCate()
        this.editDialogVisible = false
      })
    },

    //  删除分类参数
    async deleteParams (id, catid) {
      const confirmResult = await this.$confirm(
        '该操作会永久删除属性，是否继续操作',
        '提示',
        {
          confirmButtonText: '确定',
          confirmButtonText: '取消',
          type: 'warning'
        }
      ).catch((error) => error)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除！')
      const { data: res } = await this.$http.delete(
        `categories/${catid}/attributes/${id}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('删除分类参数成功')
      this.getParamsCate()
      console.log(res)
    },

    //  添加参数项的事件  @keyup.enter.native="handleInputConfirm":监听键盘按下Enter键的事件
    handleInputConfirm (row) {
      //  如果没有输入内容或者输入的内容是空格
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //  如果输入的内容正确进行后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },

    //  删除分类参数项的事件
    async saveAttrVals (row) {
      //  发起请求
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.id}`, {
        attr_name: row.attr_name,
        attr_vals: row.attr_vals,
        attr_sel: row.attr_sel
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success('修改参数项成功')
    },

    //  显示文本框的按钮事件
    showInput (row) {
      row.inputVisible = true
      //  $nextTick：当页面上元素被重新渲染之后才会执行后面的回调函数
      this.$nextTick(() => {
        //  使文本框自动获取焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    //  删除分类参数项的事件
    deleteValsClose (i, row) {
      //  把当前点击的索引传入，然后把当前的vals值的当前索引下的内容删除
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }

  },
  created () {
    this.getCateList()
  },
  //  设置计算属性
  computed: {
    //  控制按钮的禁用和启用
    isBtnDisabled () {
      if (this.selectKeys.length !== 3) {
        return true
      }

      return false
    },

    //  标题
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin-top: 15px;
}
.el-tag {
  margin: 15px;
}
.input-new-tag {
  width: 120px;
}
</style>
